﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace JZ.Common
{
    public static class ImageHelper
    {
        public static void ResizeImage(string original, string target, double maxLength)
        {
            double ratio = 1;
            Image image = null;
            Bitmap bmp = null;

            try
            {
                image = Image.FromFile(original);
                if (image.Width > maxLength || image.Height > maxLength)
                {
                    double width, height;
                    if (image.Width > image.Height)
                    {
                        ratio = maxLength / (double)image.Width;
                        width = maxLength;
                        height = (int)(image.Height * ratio);
                    }
                    else
                    {
                        ratio = maxLength / (double)image.Height;
                        height = maxLength;
                        width = (int)(image.Width * ratio);
                    }

                    bmp = new Bitmap(image, new Size((int)width, (int)height));
                    bmp.Save(target, ImageFormat.Jpeg);
                }
                else
                {
                    File.Copy(original, target);
                }
            }
            finally
            {
                if (image != null)
                {
                    image.Dispose();
                }

                if (bmp != null)
                {
                    bmp.Dispose();
                }
            }
        }
    }
}
